<template>
	<view class="container">
		<view class="form-box">
			<view class="title">注册</view>
			<view class="input-box">
				<input type="text" class="input" placeholder="请输入用户名" v-model="username" @blur="validateUsername" />
				<text v-if="usernameError" class="error-text">{{ usernameError }}</text>
			</view>
			<view class="input-box">
				<input type="password" class="input" placeholder="请输入密码" v-model="password" @blur="validatePassword" />
				<text v-if="passwordError" class="error-text">{{ passwordError }}</text>
			</view>
			<view class="input-box">
				<input type="password" class="input" placeholder="请再次输入密码" v-model="confirmPassword"
					@blur="validateConfirmPassword" />
				<text v-if="confirmPasswordError" class="error-text">{{ confirmPasswordError }}</text>
			</view>
			<button class="register-btn" @click="register" :disabled="!canRegister">注册</button>
		</view>
	</view>
</template>

<script>
	import {
		uuid
	} from '@/utils/index.js'
	export default {
		data() {
			return {
				username: '',
				password: '',
				confirmPassword: '',
				usernameError: '',
				passwordError: '',
				confirmPasswordError: '',
				canRegister: false,
				// 用户数组
				userArr: []
			};
		},
		created() {
			if (uni.getStorageSync("userArr")) {
				this.userArr = uni.getStorageSync("userArr")
			} else {
				this.userArr = []
			}
		},
		methods: {
			validateUsername() {
				this.usernameError = '';
				if (!this.username.trim()) {
					this.usernameError = '用户名不能为空';
				} else if (!/^[a-zA-Z0-9_]+$/.test(this.username)) {
					this.usernameError = '用户名只能包含字母、数字和下划线';
				}
				this.updateCanRegister();
			},
			validatePassword() {
				this.passwordError = '';
				if (!this.password.trim()) {
					this.passwordError = '密码不能为空';
				} else if (this.password.length < 6) {
					this.passwordError = '密码长度不能少于6位';
				}
				this.updateCanRegister();
			},
			validateConfirmPassword() {
				this.confirmPasswordError = '';
				if (this.password !== this.confirmPassword) {
					this.confirmPasswordError = '两次输入的密码不一致';
				}
				this.updateCanRegister();
			},
			updateCanRegister() {
				this.canRegister = !(this.usernameError || this.passwordError || this.confirmPasswordError);
			},
			register() {
				const userIfor = {
					id: uuid(),
					username: this.username,
					password: this.password
				}
				this.userArr.push(userIfor)
				uni.setStorageSync('userArr', this.userArr)
				uni.showToast({
					title: '注册成功！',
					duration: 2000
				})
				uni.navigateTo({
					url: '/pages/login/index'
				})
			}
		}
	};
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		color: #fff;
		text-align: center;
		font-size: 54.74rpx;
	}

	.input-box {
		border: 1.82rpx solid #fff;
		color: #fff;
	}

	.input-box {
		margin-bottom: 54.74rpx;
	}
</style>